package cn.yanhu.kuwanapp.utils.ext

import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.BaseFragment
import cn.yanhu.kuwanapp.http.status.BaseBean
import cn.yanhu.kuwanapp.http.status.CustomException
import cn.yanhu.kuwanapp.http.status.ResultState


/**
 * 显示页面状态，这里有个技巧，成功回调在第一个，其后两个带默认值的回调可省
 * @param resultState 接口返回值
 * @param onLoading 加载中
 * @param onSuccess 成功回调
 * @param onError 失败回调
 *
 */
fun <T> BaseActivity<*, *>.parseState(resultState: ResultState<T>, onSuccess: (T) -> Unit, onError: ((CustomException) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
            if (resultState.data != null) onSuccess(resultState.data)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e) }
        }
    }
}

/**
 * 如果需要处理返回值，用这里的code
 *
 * @param T
 * @param resultState
 * @param onSuccess
 * @param onError
 * @param onSucNull
 */
fun <T> BaseActivity<*, *>.parseState2(resultState: ResultState<BaseBean<T>>, onSuccess: (BaseBean<T>?) -> Unit, onError: ((CustomException) -> Unit)? = null, onSucNull: ((Any?) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
           onSuccess(resultState.data)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e) }
        }
    }
}

fun <T> BaseFragment<*, *>.parseState(resultState: ResultState<T>, onSuccess: (T) -> Unit, onError: ((CustomException) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
            if (resultState.data != null) onSuccess(resultState.data)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e) }
        }
    }
}

